package com.luoling.zipRead;

import com.luoling.shell.ZipShell;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.HashMap;

/**
 * Description:
 * Copyright:   Copyright (c)2024
 * Company:
 *
 * @author: 张李鑫
 * @version: 1.0 302 Moved Temporarily
 * Create at:   2024-07-09 17:41:38
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2024-07-09     张李鑫                     1.0         1.0 Version
 */
public class ZipRead {

    public static String dwPre = "dwhs";//单位账 dw
    public static String dwPreStr = "dwz";
    public static String zzPreStr = "zzzbz";
    public static String zzPre = "sqxxz999";//总账 指标 pay

    public static final String tempFileName = ".DS_Store";

    public static String DirPath = System.getProperty("user.dir") + File.separator;
//    public static String zipPrePath = File.separator + pre + File.separator + pre + File.separator;


    public static void main(String[] args) throws Exception {
        zipSqlFile("/0730/07-29核算总账单位账.sql");
        zipSqlFile("/0730/07-29表内总账单位账.sql");
        zipSqlFile("/0730/07-29表间总账单位账.sql");

    }


    /**
     * 根据.sql文件的方式处理sql 会把sql文件根据;拆分成多个文件 并且创建对应的文件夹 进行zip 压缩
     * sql文件要放在根目录下
     *
     * @param fileName
     * @param zipTypeName
     * @throws Exception
     */
    public static String zipSqlFile(String fileName) throws Exception {
        String path = splitAndCreateSQLFiles(DirPath + fileName);
        HashMap<String, String> map = new HashMap<>();
        zip(map, path);
        copyFile(map, path);
        removeDir(path);
        return path;
    }


    public static void removeDir(String path) throws IOException {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                FileUtils.deleteDirectory(file1);
            }
        }
    }


    public static void copyFile(HashMap<String, String> map, String prePath) {

        map.forEach((k, v) -> {
            try {
                Files.copy(
                        Paths.get(v + File.separator + k + ".zip"),
                        Paths.get(prePath + File.separator + k + ".zip"),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }


    public static void zip(HashMap<String, String> fileNameSet, String prePath) throws Exception {
        File file = new File(prePath);
        File[] files = file.listFiles();


        for (File file1 : files) {
            if (file1.getName().equals(tempFileName)) {
                continue;
            }
            HashMap<String, String> params = new HashMap<>();
            ZipShell zipShell = new ZipShell(params);
            params.put("directory", file1.getPath());

            String[] split = file1.getPath().split(File.separator);
            String name = split[split.length - 1];
            fileNameSet.put(name, file1.getPath());
            String pre = name.contains("dw") ? dwPre : zzPre;
            params.put("zipName", split[split.length - 1]);
            params.put("pre", pre);
            zipShell.execute();
        }
        System.out.println("zipSqlFile success");
    }


    /**
     * 读取整个.sql文件
     *
     * @param sqlFilePath
     * @param zipTypeName
     */
    public static String splitAndCreateSQLFiles(String sqlFilePath) {
        String zipPath = DirPath + "zip" + new Date().getTime() + File.separator;
        try (BufferedReader reader = new BufferedReader(new FileReader(sqlFilePath))) {
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            // 将整个文件内容作为一个字符串
            String sqlContent = sb.toString();

            // 分割SQL语句，以分号为分隔符
            String[] sqlStatements = sqlContent.split(";");


            // 创建每个SQL语句的单独文件
            for (int i = 0; i < sqlStatements.length; i++) {
                String sql = sqlStatements[i].trim();
                if (!sql.isEmpty()) {


                    String[] split = sql.split("\n");
                    String name = split[0].replace("--", "").replace(" ", "");
                    String pre = name.contains("dw") ? dwPre : zzPre;
                    String preStr = pre.equals(dwPre) ? dwPreStr : zzPreStr;
                    String zipPrePath = File.separator + pre + File.separator + pre + File.separator;

                    String prePath = zipPath + preStr;
                    Files.createDirectories(Paths.get(prePath + name + zipPrePath));
                    // 文件名从1开始递增
                    String fileName = prePath + name + zipPrePath + name + ".sql";
                    writeToFile(fileName, split[split.length - 1]);
                }
            }

            System.out.println("SQL files created successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return zipPath;
    }


    public static void writeToFile(String fileName, String content) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
